package com.sgu6.sgu6_machine.ui.fragment.set;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sgu6.middleware.enums.MachineCmdEnum;
import com.sgu6.middleware.manager.ThreadManager;
import com.sgu6.middleware.util.HexUtil;
import com.sgu6.serialport.manager.SerialPortManager;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.base.BaseF;
import com.sgu6.sgu6_machine.config.MachineConfig;
import com.sgu6.sgu6_machine.config.MotorConfig;
import com.sgu6.sgu6_machine.container.MachineContainer;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 电机设置
 */
public class CoherentActionF extends BaseF {

    @BindView(R.id.etMillTime)
    EditText etMillTime;
    @BindView(R.id.etDropTime)
    EditText etDropTime;
    @BindView(R.id.etPullTime)
    EditText etPullTime;
    @BindView(R.id.etPackTime)
    EditText etPackTime;
    @BindView(R.id.etGapTime)
    EditText etGapTime;
    @BindView(R.id.tv_mill_test_count)
    TextView tvMillTestCount;
    @BindView(R.id.tv_pack_test_count)
    TextView tvPackTestCount;
    @BindView(R.id.btn_start_mill_test)
    Button btnStartMillTest;
    @BindView(R.id.btn_stop_mill_test)
    Button btnStopMillTest;
    @BindView(R.id.btn_reset_mill_test)
    Button btnResetMillTest;
    @BindView(R.id.btn_start_pack_test)
    Button btnStartPackTest;
    @BindView(R.id.btn_stop_pack_test)
    Button btnStopPackTest;
    @BindView(R.id.btn_reset_pack_test)
    Button btnResetPackTest;
    @BindView(R.id.et_open_door_time)
    EditText etOpenDoorTime;
    @BindView(R.id.et_close_door_time)
    EditText etCloseDoorTime;
    @BindView(R.id.et_door_gap_time)
    EditText etDoorGapTime;
    @BindView(R.id.tv_door_test_count)
    TextView tvDoorTestCount;
    @BindView(R.id.btn_start_door_test)
    Button btnStartDoorTest;
    @BindView(R.id.btn_stop_door_test)
    Button btnStopDoorTest;
    @BindView(R.id.btn_reset_door_test)
    Button btnResetDoorTest;
    @BindView(R.id.etMillTestCount)
    EditText etMillTestCount;
    @BindView(R.id.et_door_test_count)
    EditText etDoorTestCount;
    @BindView(R.id.ll_container)
    LinearLayout llContainer;

    private List<MotorConfig> motorConfigs = new ArrayList<>();
    private List<String> startCommands = new ArrayList<>();
    private List<String> stopCommands = new ArrayList<>();
    private EditText etTimes, etGap, etLauncherTime;
    private String strTimes, strGap, strLauncherTime;
    private String strActionMill, strActionDrop, strActionPull, strActionPack, strActionGap, strActionOpen, strActionClose, strActionDoorGap;
    private int millCount = 0, millTotal = 0, packCount = 0, packTotal = 0, doorCount = 0, doorTotal = 0;
    private boolean isMilling = false, isPacking = false, isDooring = false;


    public static CoherentActionF newInstance() {
        return new CoherentActionF();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_coherent_action, container, false);
        unbinder = ButterKnife.bind(this, v);
        init();

        return v;
    }

    private void init() {
        motorConfigs.add(new MotorConfig("碾米电机：", 1, 5000, 0, 5));
        motorConfigs.add(new MotorConfig("拉膜电机：", 1, 5000, 0, 2));
        motorConfigs.add(new MotorConfig("下米电机：", 1, 5000, 0, 5));
        motorConfigs.add(new MotorConfig("封膜电机：", 1, 5000, 0, 5));
        motorConfigs.add(new MotorConfig("开关门电机：", 1, 5000, 0, 20));

        startCommands.add(MachineCmdEnum.启动碾米电机.code());
        startCommands.add(MachineCmdEnum.启动拉膜电机.code());
        startCommands.add(MachineCmdEnum.启动下米电机.code());
        startCommands.add(MachineCmdEnum.启动封膜电机.code());
        startCommands.add(MachineCmdEnum.开门电机开到位.code());

        stopCommands.add(MachineCmdEnum.立即关闭碾米电机.code());
        stopCommands.add(MachineCmdEnum.立即关闭拉膜电机.code());
        stopCommands.add(MachineCmdEnum.立即关闭下米电机.code());
        stopCommands.add(MachineCmdEnum.立即关闭封膜电机.code());
        stopCommands.add(MachineCmdEnum.开门电机关到位.code());

        if (!MachineContainer.machineConfigDto.withPack){
            llContainer.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void getStartValue(View parent) {
        etTimes = parent.findViewById(R.id.et_times);
        strTimes = etTimes.getText().toString().trim();

        etGap = parent.findViewById(R.id.et_gap);
        strGap = etGap.getText().toString().trim();

        etLauncherTime = parent.findViewById(R.id.et_launcher_time);
        strLauncherTime = etLauncherTime.getText().toString().trim();
    }


    @OnClick({R.id.btn_start_mill_test, R.id.btn_stop_mill_test, R.id.btn_reset_mill_test, R.id.btn_start_pack_test, R.id.btn_stop_pack_test, R.id.btn_reset_pack_test, R.id.btn_start_door_test, R.id.btn_stop_door_test, R.id.btn_reset_door_test})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_start_mill_test: //开始碾米测试
                isMilling = true;
                strActionMill = etMillTime.getText().toString().trim();
                strActionDrop = etDropTime.getText().toString().trim();
                strActionPull = etPullTime.getText().toString().trim();
                strActionPack = etPackTime.getText().toString().trim();
                strActionGap = etGapTime.getText().toString().trim();
                millTotal = Integer.parseInt(etMillTestCount.getText().toString().trim());

                ThreadManager.getThreadPollProxy().execute(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            if (millCount < millTotal && isMilling) {
                                try {
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.启动碾米电机.code()));
                                    Thread.sleep(Integer.parseInt(strActionMill) * 1000);
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.立即关闭碾米电机.code()));
                                    Thread.sleep(500);
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.启动下米电机.code()));
                                    Thread.sleep(Integer.parseInt(strActionDrop) * 1000);
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.立即关闭下米电机.code()));
                                    Thread.sleep(500);
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.启动拉膜电机.code()));
                                    Thread.sleep(Integer.parseInt(strActionPull) * 1000);
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.立即关闭拉膜电机.code()));
                                    Thread.sleep(500);
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.启动封膜电机.code()));
                                    Thread.sleep(Integer.parseInt(strActionPack) * 1000);
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.立即关闭封膜电机.code()));
                                    Thread.sleep(Integer.parseInt(strActionGap) * 1000);
                                    millCount++;
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvMillTestCount.setText(String.valueOf(millCount));
                                        }
                                    });
                                } catch (Exception e) {
                                    Log.i(TAG, "run: " + e.getLocalizedMessage());
                                }
                            } else {
                                isMilling = false;
                                break;
                            }

                        }
                    }
                });

                break;
            case R.id.btn_stop_mill_test:
                isMilling = false;
                break;
            case R.id.btn_reset_mill_test:
                millCount = 0;
                isMilling = false;
                tvMillTestCount.setText("0");
                break;
            case R.id.btn_start_pack_test:
                isPacking = true;
                strActionDrop = etDropTime.getText().toString().trim();
                strActionPull = etPullTime.getText().toString().trim();
                strActionPack = etPackTime.getText().toString().trim();
                strActionGap = etGapTime.getText().toString().trim();
                packTotal = Integer.parseInt(etMillTestCount.getText().toString().trim());

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            if (packCount < packTotal && isPacking) {
                                try {
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.启动下米电机.code()));
                                    Thread.sleep(Integer.parseInt(strActionDrop) * 1000);
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.立即关闭下米电机.code()));
                                    Thread.sleep(500);
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.启动拉膜电机.code()));
                                    Thread.sleep(Integer.parseInt(strActionPull) * 1000);
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.立即关闭拉膜电机.code()));
                                    Thread.sleep(500);
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.启动封膜电机.code()));
                                    Thread.sleep(Integer.parseInt(strActionPack) * 1000);
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.立即关闭封膜电机.code()));
                                    Thread.sleep(Integer.parseInt(strActionGap) * 1000);
                                    packCount++;
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvPackTestCount.setText(String.valueOf(packCount));
                                        }
                                    });
                                } catch (Exception e) {
                                    Log.i(TAG, "run: " + e.getLocalizedMessage());
                                }
                            } else {
                                isPacking = false;
                                break;
                            }

                        }
                    }
                }).start();

                break;
            case R.id.btn_stop_pack_test:
                isPacking = false;
                break;
            case R.id.btn_reset_pack_test:
                packCount = 0;
                isPacking = false;
                tvPackTestCount.setText("0");
                break;
            case R.id.btn_start_door_test:
                isDooring = true;
                strActionOpen = etMillTime.getText().toString().trim();
                strActionClose = etPackTime.getText().toString().trim();
                strActionDoorGap = etGapTime.getText().toString().trim();
                doorTotal = Integer.parseInt(etDoorTestCount.getText().toString().trim());

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            if (doorCount < doorTotal && isDooring) {
                                try {
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.开门电机开到位.code()));
                                    Thread.sleep(Integer.parseInt(strActionOpen) * 1000);
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.开门电机关到位.code()));
                                    Thread.sleep(Integer.parseInt(strActionClose) * 1000);
                                    SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.立即停止开门电机.code()));
                                    Thread.sleep(Integer.parseInt(strActionDoorGap) * 1000);
                                    doorCount++;
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            tvDoorTestCount.setText(String.valueOf(doorCount));
                                        }
                                    });
                                } catch (Exception e) {
                                    Log.i(TAG, "run: " + e.getLocalizedMessage());
                                }
                            } else {
                                isDooring = false;
                                break;
                            }

                        }
                    }
                }).start();

                break;
            case R.id.btn_stop_door_test:
                isDooring = false;
                break;
            case R.id.btn_reset_door_test:
                doorCount = 0;
                isDooring = false;
                tvDoorTestCount.setText("0");
                break;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.i(TAG, "onHiddenChanged: " + hidden);
//        if (hidden) {
//            SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.自动模式.code()));
//        } else {
//            SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.手动模式.code()));
//        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
